# 作者：要努力，努力，再努力
# 开发时间：2022/4/27 20:45

import os

filename = 'good.txt'


def main():
    print('输入数据：')
    show()
    # insert()
    # show()
    car()


def insert():
    good_lst = []
    while True:
        try:
            id = int(input('请输入商品ID：'))
        except:
            print('输入的id格式不正确')
            break
        name = input('请输入商品名：')
        if not name:
            flag = False
            break
        good_lst.append({'id': id, 'name': name})
        answer = input('是否继续录入？y/n')
        if answer == 'y':
            continue
        else:
            break
    # 保存商品信息
    save(good_lst)
    print('录入信息成功！')


def save(lst):
    try:
        file = open(filename, 'a', encoding='utf-8')
    except:
        file = open(filename, 'w', encoding='utf-8')

    for item in lst:
        file.write(str(item) + '\n')
    file.close()


def show():
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            good_list = rfile.readlines()
        if len(good_list) == 0:
            print('没有学生信息')
        else:
            # 显示标题
            format_title = "{:^6}\t{:^12}\t"
            print(format_title.format('ID', '商品名'))
            # 显示内容
            format_data = "{:^6}\t{:^12}\t"
            for item in good_list:
                ditem = dict(eval(item))
                print(format_data.format(ditem.get('id'),
                                         ditem.get('name')
                                         ))
    else:
        print('无数据')
        return


car_list = []


def car():
    while True:
        num = input('请输入商品编号：')
        if num.isdigit():
            with open(filename, 'r', encoding='utf-8') as rfile:
                good_list = rfile.readlines()
            for item in good_list:
                if item.find(num) != -1:
                    car_list.append(item)
                    break
        elif num == 'q':
            print('退出')
            break
        else:
            print('输入有误，请重新输入')
            continue
    for m in car_list:
        print(m)


if __name__ == '__main__':
    main()
